<template>
  <el-card>
    <el-button type="primary" icon="Plus" @click="tradeMarkEdit('add', undefined)">添加品牌</el-button>
    <el-table border style="margin: 10px 0px;" :data="tradeMarkData">
      <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
      <el-table-column label="品牌名称" align="center">
        <!-- 使用插槽自定义 -->
        <template #="{ row, $index }">
          <pre>{{ row.tmName }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO" align="center">
        <template #="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 40px;height: 40px">
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" align="center">
        <template #="{ row }">
          <el-button type="primary" icon="Edit" @click="tradeMarkEdit('edit', row)"></el-button>
          <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled"
            icon-color="#626AEF" title="确认要删除该品牌吗?" @confirm="tradeMarkDel(row.id)">
            <template #reference>
              <el-button type="danger" icon="Delete"></el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20]" background
      small layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" center>
      <el-form :model="tradeMarkForm" ref="tradeMarkRef" :rules="formRules">
        <el-form-item label="品牌名称" required prop="tmName">
          <el-input v-model="tradeMarkForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo" required prop="logoUrl">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handlePictureSuccess" :before-upload="beforePictureUpload">
            <img v-if="tradeMarkForm.logoUrl" :src="tradeMarkForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm(tradeMarkRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>

</template>
<script setup lang='ts'>
import { nextTick, onBeforeMount, onMounted, reactive, ref } from 'vue'
import { getTrademarkList, addTradeMark, delTradeMark, editTradeMark } from '@/api/product/trademark/index.ts'
import { Records, tradeMarkListRes } from '@/api/product/type.ts'
import { ElMessage, ElNotification, type UploadProps, type FormInstance } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
let currentPage = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let tradeMarkData = ref<Records>([])
let dialogVisible = ref<boolean>(false)
let dialogTitle = ref<string>('')
let tradeMarkForm = reactive({
  tmName: '',
  logoUrl: '',
})
let rowId = ref<any>(undefined)
let tradeMarkRef = ref<FormInstance>()
// 表单校验规则
let formRules = reactive({
  tmName: [
    { required: true, message: '品牌名称为必填项', trigger: blur },
    { min: 6, max: 10, message: '品牌名称必须为6到10位' }
  ],
})
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // 重新请求接口
  trademarkList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 重新请求接口
  trademarkList()
}
const trademarkList = async () => {
  let result: tradeMarkListRes = await getTrademarkList(currentPage.value, pageSize.value)
  const { code, data, message } = result
  if (code == 200) {
    total.value = data.total
    tradeMarkData.value = data.records
  }
}
// 编辑品牌
const tradeMarkEdit = (val: string, row: any) => {
  switch (val) {
    // 新增品牌
    case 'add':
      console.log(22);
      dialogTitle.value = '添加品牌'
      console.log(tradeMarkForm);
      break;
    // 修改品牌
    case 'edit':
      dialogTitle.value = '修改品牌'
      if (row) {
        nextTick(() => {
          tradeMarkForm.tmName = row.tmName
          tradeMarkForm.logoUrl = row.logoUrl
          rowId.value = row.id
        })
      }
      break;
    default:
      dialogTitle.value = '添加品牌'
      break;
  }
  dialogVisible.value = true
}
// 删除品牌

const tradeMarkDel = (id: number) => {
  delTradeMark(id).then(res => {
    console.log(res);
    if (res.code == 200) {
      // 重新获取当前列表
      trademarkList()
    } else {
      ElMessage.error('删除品牌失败')
    }
  })
}
// dialog的确认事件
const confirm = async (formEl: FormInstance | undefined) => {
  // 校验表单项
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (dialogTitle.value == '添加品牌') {
        addTradeMark({
          tmName: tradeMarkForm.tmName,
          logoUrl: tradeMarkForm.logoUrl
        }).then(res => {
          console.log(res);
          if (res.code == 200) {
            dialogVisible.value = false
          } else {
            ElMessage.error('添加品牌失败')
          }
        })
      } else {
        // 调用修改接口
        editTradeMark({
          id: rowId.value,
          tmName: tradeMarkForm.tmName,
          logoUrl: tradeMarkForm.logoUrl
        }).then(res => {
          if (res.code == 200) {
            ElMessage.success('修改品牌成功')
            dialogVisible.value = false
            // 重新获取数据
            trademarkList()
            // 清空表单中的数据
            tradeMarkRef.value?.resetFields()
          } else {
            ElMessage.error('修改品牌失败')
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 取消按钮点击事件
const cancel = () => {
  dialogVisible.value = false
  tradeMarkRef.value?.resetFields()
}
// 图片上传成功回调函数
const handlePictureSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  tradeMarkForm.logoUrl = response.data
}
// 在上传之前回调函数
const beforePictureUpload: UploadProps['beforeUpload'] = (rowFile) => {
  if (rowFile.type == 'image/jpeg' || rowFile.type == 'image/png' || rowFile.type == 'image/gif') {
    if (rowFile.size / 1024 / 1024 > 4) {
      ElNotification.error('上传图片不能超过4M')
      return false
    } else {
      return true
    }
  } else {
    ElNotification.error('请上传png、jpeg、gif类型的图片')
    return false
  }
}
onBeforeMount(() => {

})
onMounted(() => {
  // 获取品牌列表数据
  trademarkList()
})

</script>
<style lang="scss" scoped></style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>